package etnorservice.etnor_service.service;

import etnorservice.etnor_service.domain.MenuItemDomain;
import etnorservice.etnor_service.domain.RolePermissionDomain;
import etnorservice.etnor_service.mapper.MenuMapper;
import etnorservice.etnor_service.mapper.RolePermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2025/03/24/13:02
 **/
@Service
public class MenuItemService {

    @Autowired
    private MenuMapper menuItemMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    public List<MenuItemDomain> getMenuTree() {
        List<MenuItemDomain> allMenus = menuItemMapper.getMenuTree();
        return buildTree(allMenus);
    }

    private List<MenuItemDomain> buildTree(List<MenuItemDomain> allMenus) {
        List<MenuItemDomain> rootMenus = new ArrayList<>();
        Map<Integer, List<MenuItemDomain>> childrenMap = new HashMap<>();

        System.out.println("输入的菜单列表大小：" + allMenus.size());

        // 按父ID分组
        for (MenuItemDomain menu : allMenus) {
            System.out.println("处理菜单项：id=" + menu.getId() + ", parentId=" + menu.getParentId());
            // 修改判断条件：parentId 为 0 或 null 的都是根节点
            if (menu.getParentId() == null || menu.getParentId() == 0) {
                System.out.println("添加到根节点：" + menu.getNamezh());
                rootMenus.add(menu);
            } else {
                System.out.println("添加到子节点map：parentId=" + menu.getParentId());
                childrenMap.computeIfAbsent(menu.getParentId(), k -> new ArrayList<>())
                        .add(menu);
            }
        }

        System.out.println("根节点数量：" + rootMenus.size());
        System.out.println("子节点Map大小：" + childrenMap.size());

        // 递归构建树
        for (MenuItemDomain root : rootMenus) {
            buildChildren(root, childrenMap);
        }

        return rootMenus;
    }

    private void buildChildren(MenuItemDomain parent, Map<Integer, List<MenuItemDomain>> childrenMap) {
        List<MenuItemDomain> children = childrenMap.get(parent.getId());
        System.out.println("处理节点：" + parent.getNamezh() + ", 子节点数量：" + (children != null ? children.size() : 0));

        if (children != null && !children.isEmpty()) {
            parent.setChildren(children);
            for (MenuItemDomain child : children) {
                buildChildren(child, childrenMap);
            }
        }
    }


    // 获取角色的权限列表
    public List<MenuItemDomain> getRolePermissions(Integer roleId) {
        return menuItemMapper.getRolePermissions(roleId);
    }

    // 分配角色权限
    @Transactional
    public void assignPermissions(Integer roleId, List<Integer> permissionIds) {
        // 先删除原有权限
        rolePermissionMapper.deleteByRoleId(roleId);

        // 批量插入新权限
        if (!CollectionUtils.isEmpty(permissionIds)) {
            List<RolePermissionDomain> permissions = permissionIds.stream()
                    .map(permissionId -> {
                        RolePermissionDomain rp = new RolePermissionDomain();
                        rp.setRoleId(roleId);
                        rp.setPermissionId(permissionId);
                        rp.setCreatedAt(new Date());
                        rp.setUpdatedAt(new Date());
                        return rp;
                    })
                    .collect(Collectors.toList());

            rolePermissionMapper.batchInsert(permissions);
        }
    }
    // 获取所有权限列表（树形结构）
    public List<MenuItemDomain> getAllPermissions() {
        List<MenuItemDomain> allPermissions = menuItemMapper.getAllPermissions();
        return buildTree(allPermissions);
    }

    // 添加权限
    public MenuItemDomain addPermission(MenuItemDomain permission) {
        //permission.setCreatedAt(new Date());
        menuItemMapper.insert(permission);
        return permission;
    }

    // 更新权限
    public void updatePermission(MenuItemDomain permission) {
        //permission.setUpdatedAt(new Date());
        menuItemMapper.updateById(permission);
    }

    // 删除权限
    @Transactional
    public void deletePermission(Integer id) {
        // 先删除子权限
        menuItemMapper.deleteByParentId(id);
        // 再删除当前权限
        menuItemMapper.deleteById(id);
        // 删除相关的角色权限关联
        rolePermissionMapper.deleteByPermissionId(id);
    }
}
